<template>
  <t-layout class="lg-soar-layout">
    <t-tabs
      v-if="settingStore.isUseTabsRouter"
      id="lg-soar-layout-tabs"
      theme="card"
      class="lg-soar-layout-tabs-nav"
      :value="$route.fullPath"
      :style="{ position: 'sticky', top: 0, width: '100%' }"
      drag-sort
      @change="handleChangeCurrentTab"
      @remove="handleRemove"
    >
      <t-tab-panel v-for="(item, index) in tabRouters" :key="item.path" :value="item.path" :removable="!item.isHome">
        <template #label>
          <t-dropdown
            trigger="context-menu"
            :min-column-width="128"
            :popup-props="{
              overlayClassName: 'route-tabs-dropdown',
              onVisibleChange: (visible, ctx) => handleTabMenuClick(visible, ctx, item.path),
              visible: activeTabPath === item.path,
            }"
          >
            <template v-if="!item.isHome">{{ item.title }}</template>
            <t-icon v-else name="home" />
            <template #dropdown>
              <t-dropdown-menu>
                <t-dropdown-item @click="handleRefresh(item, index)"> <t-icon name="refresh" /> 刷新 </t-dropdown-item>
                <t-dropdown-item v-if="index > 1" @click="handleCloseAhead(item.path, index)">
                  <t-icon name="arrow-left" /> 关闭左侧
                </t-dropdown-item>
                <t-dropdown-item v-if="index < tabRouters.length - 1" @click="handleCloseBehind(item.path, index)">
                  <t-icon name="arrow-right" /> 关闭右侧
                </t-dropdown-item>
                <t-dropdown-item v-if="tabRouters.length > 2" @click="handleCloseOther(item.path, index)">
                  <t-icon name="close-circle" /> 关闭其它
                </t-dropdown-item>
              </t-dropdown-menu>
            </template>
          </t-dropdown>
        </template>
      </t-tab-panel>
    </t-tabs>
    <l-breadcrumb v-if="settingStore.showBreadcrumb" id="lg-soar-layout-breadcrumb" />
    <div id="lg-soar-layout-main" class="lg-flex-col" style="flex: 1; overflow: auto; position: relative">
      <transition name="fade" mode="out-in">
        <l-content />
      </transition>
      <t-footer v-if="settingStore.showFooter" id="lg-soar-layout-footer" class="lg-soar-footer-layout">
        <l-footer />
      </t-footer>
    </div>
  </t-layout>
</template>

<script setup lang="ts">
import { computed, nextTick, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useSettingStore, useTabsRouterStore } from '@/store';
import type { TRouterInfo } from '@/types/interface';

import LContent from './Content.vue';
import LBreadcrumb from './Breadcrumb.vue';
import LFooter from './Footer.vue';
import { on } from '@/soar';

const route = useRoute();
const router = useRouter();

const settingStore = useSettingStore();
const tabsRouterStore = useTabsRouterStore();

const activeTabPath = ref('');

const tabRouters = computed(() => tabsRouterStore.tabRouters);

const handleChangeCurrentTab = (path: string) => {
  const { tabRouters } = tabsRouterStore;
  const info = tabRouters.find((i) => i.path === path);
  router.push({ path, query: info.query });
};

const handleRemove = ({ value: path, index }) => {
  const { tabRouters } = tabsRouterStore;
  const nextRouter = tabRouters[index + 1] || tabRouters[index - 1];

  tabsRouterStore.subtractCurrentTabRouter({ path, routeIdx: index });
  if (path === route.path) router.push({ path: nextRouter.path, query: nextRouter.query });
};

const handleRefresh = (item: TRouterInfo, routeIdx: number) => {
  tabsRouterStore.toggleTabRouterAlive(routeIdx);
  nextTick(() => {
    tabsRouterStore.toggleTabRouterAlive(routeIdx);
    router.replace({ path: item.path, query: item.query });
  });
  activeTabPath.value = null;
};
const handleCloseAhead = (path: string, routeIdx: number) => {
  tabsRouterStore.subtractTabRouterAhead({ path, routeIdx });

  handleOperationEffect('ahead', routeIdx);
};
const handleCloseBehind = (path: string, routeIdx: number) => {
  tabsRouterStore.subtractTabRouterBehind({ path, routeIdx });

  handleOperationEffect('behind', routeIdx);
};
const handleCloseOther = (path: string, routeIdx: number) => {
  tabsRouterStore.subtractTabRouterOther({ path, routeIdx });

  handleOperationEffect('other', routeIdx);
};

// 处理非当前路由操作的副作用
const handleOperationEffect = (type: 'other' | 'ahead' | 'behind', routeIndex: number) => {
  const currentPath = router.currentRoute.value.path;
  const { tabRouters } = tabsRouterStore;

  const currentIdx = tabRouters.findIndex((i) => i.path === currentPath);
  // 存在三种情况需要刷新当前路由
  // 点击非当前路由的关闭其他、点击非当前路由的关闭左侧且当前路由小于触发路由、点击非当前路由的关闭右侧且当前路由大于触发路由
  const needRefreshRouter =
    (type === 'other' && currentIdx !== routeIndex) ||
    (type === 'ahead' && currentIdx < routeIndex) ||
    (type === 'behind' && currentIdx === -1);
  if (needRefreshRouter) {
    const nextRouteIdx = type === 'behind' ? tabRouters.length - 1 : 1;
    const nextRouter = tabRouters[nextRouteIdx];
    router.push({ path: nextRouter.path, query: nextRouter.query });
  }

  activeTabPath.value = null;
};
const handleTabMenuClick = (visible: boolean, ctx, path: string) => {
  if (ctx.trigger === 'document') activeTabPath.value = null;
  if (visible) activeTabPath.value = path;
};

on('closeTab', (path) => {
  if (settingStore.isUseTabsRouter) {
    tabsRouterStore.closeCurrentTabRouter(path ?? route.fullPath);
  }
});
</script>

<style lang="less">
.lg-soar-layout-tabs-nav {
  .t-tabs__btn.t-size-m,
  .t-tabs__nav-item.t-size-m {
    height: var(--app-height-component);
  }
}
.fade-leave-active,
.fade-enter-active {
  transition: opacity @anim-duration-slow @anim-time-fn-easing;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
